#include "chip.h"
#include <QPainter>

Chip::Chip(const QString& label, QGraphicsItem *parent)
    : CircuitComponent(parent)
    , m_label(label)
{
    // 设置芯片默认尺寸
    setFlag(QGraphicsItem::ItemIsSelectable);
}

QPointF Chip::inputPort() const
{
    return QPointF(-40, 0); // 左侧引脚
}

QPointF Chip::outputPort() const
{
    return QPointF(40, 0);  // 右侧引脚
}

void Chip::setLabel(const QString& label)
{
    m_label = label;
    update();
}

QRectF Chip::boundingRect() const
{
    return QRectF(-50, -30, 100, 60); // 包含文本和引脚
}

void Chip::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);

    // 绘制芯片主体
    painter->setPen(QPen(Qt::darkGray, 2));
    painter->setBrush(QColor(240, 240, 240));
    painter->drawRoundedRect(-40, -25, 80, 50, 10, 10);

    // 绘制引脚
    painter->setPen(Qt::black);
    for(int y : {-PIN_SPACING, PIN_SPACING}) {
        painter->drawRect(-45, y-5, 10, 10);  // 左侧输入
        painter->drawRect(35, y-5, 10, 10);   // 右侧输出
    }

    // 绘制标签
    painter->setPen(Qt::white);
    QFont font = painter->font();
    font.setPointSize(8);
    painter->setFont(font);
    painter->drawText(QRectF(-35, -15, 70, 30), Qt::AlignCenter, m_label);
}
